import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

import { throwHttpException1 } from '@/utils/nesjUtils';
import prismaClient from '@/config/prismaClient';
import { IBatchDelApiParams } from '../types';
// 校验密码
@Injectable()
class CheckParamIsEmptyMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    const body = req.body as IBatchDelApiParams;
    // console.log('123', req.body);
    // 1、校验整体参数是否传递
    if (Object.keys(body).length == 0) {
      throwHttpException1({
        state: '0',
        msg: '请检查参数是否正确！',
        data: '',
      });
    }
    if (!body.IDs) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！必填项: IDs`,
        data: '',
      });
    }
    next();
  }
}
@Injectable()
class CheckIDsIsExistMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    const body = req.body as IBatchDelApiParams;
    const ids = body.IDs.split(',');
    if (ids.length != 0) {
      const errRows = [];
      for (const id of ids) {
        const res = await prismaClient.base_user.findMany({
          where: {
            ID: id,
            IsDel: '0',
          },
        });
        if (res.length == 0) {
          errRows.push(id);
        }
      }
      if (errRows.length != 0) {
        throwHttpException1({
          state: '0',
          msg: `请检查参数是否正确！以下ID未找到: ${errRows.join()}`,
          data: '',
        });
      }

      next();
    }
  }
}

export default {
  CheckParamIsEmptyMiddleware,
  CheckIDsIsExistMiddleware,
};
